﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using static WinForm_Mes.CheckManagement
    .检验单据; // 引用DocumentDto

namespace WinForm_Mes.CheckManagement
{
    public partial class TextDisplayForm : DevExpress.XtraEditors.XtraForm
    {
        private static readonly HttpClient httpClient = new HttpClient();
        private DocumentDto _rowData;

        public TextDisplayForm(DocumentDto rowData)
        {
            InitializeComponent();
            _rowData = rowData;
            this.Load += TextDisplayForm_Load;
            simpleButton1.Click += SimpleButton1_Click; // 合格
            simpleButton2.Click += SimpleButton2_Click; // 不合格
        }

        private void TextDisplayForm_Load(object sender, EventArgs e)
        {
            checkCode.Text = _rowData.checkCode;
            gProcessId.Text = _rowData.gProcessId;
            sampleCount.Text = _rowData.sampleCount.ToString();
            checkVersion.Text = _rowData.checkVersion;
            gProcessName.Text = _rowData.gProcessName;
            checkWay.Text = _rowData.checkWay;
            // 其它字段同理
        }

        private async Task LoadDataAsync()
        {
            try
            {
                // 这里可以根据需要拼接参数
                string url = "http://localhost:5295/api/CheckStandard/GetAllCheck?PageIndex=1&PageSize=1";
                var response = await httpClient.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    // 假设返回结构为 { items: [ {...} ], ... }
                    var result = JsonConvert.DeserializeObject<ApiResult>(json);
                    if (result != null && result.items != null && result.items.Count > 0)
                    {
                        var data = result.items[0];
                        // 显示到控件
                        checkCode.Text = data.checkCode;
                        gProcessId.Text = data.gProcessId;
                        sampleCount.Text = data.sampleCount.ToString();
                        checkVersion.Text = data.checkVersion;
                        gProcessName.Text = data.gProcessName;
                        gProcessName.Text = data.checkWay;
                        // 其它控件赋值
                    }
                }
                else
                {
                    XtraMessageBox.Show("接口请求失败：" + response.ReasonPhrase);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("异常：" + ex.Message);
            }
        }

        // 用于反序列化API返回结构
        public class ApiResult
        {
            public List<CheckData> items { get; set; }
        }

        private async void SimpleButton1_Click(object sender, EventArgs e)
        {
            await SubmitResultAsync(true);
        }

        private async void SimpleButton2_Click(object sender, EventArgs e)
        {
            await SubmitResultAsync(false);
        }

        private async Task SubmitResultAsync(bool isOk)
        {
            try
            {
                var req = new ResultRequest
                {
                    checkCode = checkCode.Text,

                    gProcessId = gProcessId.Text,
                    gProcessName = gProcessName.Text,
                    checkWay = checkWay.Text,
                    checkVersion = checkVersion.Text,
                    sampleCountSum = int.TryParse(sampleCount.Text, out int sum) ? sum : 0,
                    sampleCount = 0,
                    passCount = 0,
                    inspector = "admin"
                };

                string url = isOk
                    ? "http://localhost:5295/api/Result/AddResultOK"
                    : "http://localhost:5295/api/Result/AddResultNO";

                var content = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    // 提交成功后，查询合格/不合格数
                    var resultCount = await GetResultCountAsync(req.checkCode);

                    // 显示到页面
                    SampleCounts.Text = resultCount.sampleCounts.ToString();
                    PassCounts.Text = resultCount.passCounts.ToString();

                    int total = resultCount.sampleCounts + resultCount.passCounts;
                    int required = req.sampleCountSum;

                    if (total >= required)
                    {
                        XtraMessageBox.Show("检验完毕！");
                        this.Close();
                    }
                    else
                    {
                        XtraMessageBox.Show($"当前已检验：{total}/{required}，请继续检验。");
                    }
                }
                else
                {
                    string msg = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show("提交失败：" + msg);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("异常：" + ex.Message);
            }
        }

        private async Task<ResultCount> GetResultCountAsync(string checkCode)
        {
            string url = $"http://localhost:5295/api/Result/GetResull?checkCode={Uri.EscapeDataString(checkCode)}";
            var response = await httpClient.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                string json = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<ResultCountResponse>(json);
                return result?.data ?? new ResultCount();
            }
            return new ResultCount();
        }

        private void memoEdit1_EditValueChanged(object sender, EventArgs e)
        {

        }
    }

    public class CheckData
    {
        public string checkCode { get; set; }
        public string gProcessId { get; set; }
        public int sampleCount { get; set; }
        public string checkVersion { get; set; }
        public string gProcessName { get; set; }
        public string checkWay { get; set; }
        // 其它你页面上有的字段
    }

    public class ResultRequest
    {
        public string checkCode { get; set; }
        public string gProcessId { get; set; }
        public string gProcessName { get; set; }
        public string checkWay { get; set; }
        public string checkVersion { get; set; }
        public int sampleCountSum { get; set; }
        public int sampleCount { get; set; } = 0;
        public int passCount { get; set; } = 0;
        public string inspector { get; set; }
    }

    public class ResultCount
    {
        public string checkCode { get; set; }
        public string gProcessId { get; set; }
        public string gProcessName { get; set; }
        public string checkWay { get; set; }
        public int sampleCountSum { get; set; }
        public string checkVersion { get; set; }
        public int sampleCounts { get; set; } // 不合格数
        public int passCounts { get; set; }   // 合格数
        public string inspector { get; set; }
        public DateTime inspectDate { get; set; }
    }

    public class ResultCountResponse
    {
        public int code { get; set; }
        public string message { get; set; }
        public ResultCount data { get; set; }
    }
}